package com.restaurant.springboot.utils;

import com.restaurant.springboot.entity.WechatInfoEntity;
import com.restaurant.springboot.entity.WechatOpenIdResp;
import com.restaurant.springboot.entity.WechatToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

/**
 * @Author jack
 * @Date:2019/8/1 16:15
 */
@Component
public class WechatUtil {

    @Autowired
    HttpUtil  wechatOpenIdRespHttpUtil;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 通过微信接口获取token
     * @return
     */
    public WechatToken getToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={?}&secret={?}";
        WechatToken wechatToken = (WechatToken) wechatOpenIdRespHttpUtil.getResponseEntity(
                url,
                WechatToken.class,
                Constant.APP_ID,
                Constant.SECRET);
        EhcacheUtil.setCache(cacheManager, "token", wechatToken);
        return wechatToken;
    }

    /**
     * 通过微信接口获取OPEND_ID
     * @param code 凭证
     * @return openId信息
     */
    public WechatOpenIdResp getWechatOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={?}&secret={?}&js_code={?}&grant_type=authorization_code";
        WechatOpenIdResp wechatopenidresp = (WechatOpenIdResp)wechatOpenIdRespHttpUtil.getResponseEntity(
                url,
                WechatOpenIdResp.class,
                Constant.APP_ID,
                Constant.SECRET,code
                );
        return wechatopenidresp;
    }

    /**
     * 获取用户信息
     * @param openId 用户身份证
     * @return 结果
     */
    public WechatInfoEntity getWechatInfo(String openId){
        WechatToken wechatToken = (WechatToken) EhcacheUtil.getCache(cacheManager, "token");
        if(wechatToken == null){ //获取缓存失败
            wechatToken = getToken();
        }
        if(wechatToken == null){
            return null; //再次访问失败
        }
        String token = wechatToken.getAccess_token();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token={?}&openid={?}&lang=zh_CN";
        WechatInfoEntity wechatInfoEntity = (WechatInfoEntity) wechatOpenIdRespHttpUtil.getResponseEntity(
                url,
                WechatInfoEntity.class,
                token,
                openId
        );
        return wechatInfoEntity;
    }
}
